package com.sxt.demo.djiapplication.activity;

import static com.sxt.demo.djiapplication.common.CommonConstants.ERROR_TRACE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.sxt.demo.djiapplication.R;
import com.sxt.demo.djiapplication.dji.DJIDemoContext;
import com.sxt.demo.djiapplication.utils.ShareUtil;
import com.sxt.demo.djiapplication.view.MoveScaleRotateView;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import dji.sdk.base.BaseProduct;
import dji.sdk.products.Aircraft;
import dji.sdk.sdkmanager.DJISDKManager;

/**
 * 处理app与设备的连接
 */
public class ConnectionActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = ConnectionActivity.class.getName();
    private static final String DJIAIRCRAFT = "DJIAircraft";
    private static final String DJIHAND_HELD = "DJIHandHeld";

    private TextView mTextConnectionStatus;
    private TextView mTextProduct;
    private Button mBtnOpen;
    private static final String[] REQUIRED_PERMISSION_LIST = new String[]{
            Manifest.permission.VIBRATE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.WAKE_LOCK,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
    };
    private final List<String> missingPermission = new ArrayList<>();
    private static final int REQUEST_PERMISSION_CODE = 12345;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connection);

        initUI();

        checkAndRequestPermissions();


        // 注册广播接收器以接收设备连接状态的改变.
        IntentFilter filter = new IntentFilter();
        filter.addAction(DJIDemoContext.FLAG_CONNECTION_CHANGE);
        registerReceiver(mReceiver, filter);
        
        // 处理应用程序崩溃的错误信息日志
        handleErrorTrace();
    }

    private void handleErrorTrace() {
        File errorTrace = (File) getIntent().getSerializableExtra(ERROR_TRACE);
        if (errorTrace != null) {
            // 显示是否分享错误信息的对话框
            showErrorTraceShareDialog(errorTrace);
        }
    }

    private void showErrorTraceShareDialog(File errorTrace) {
        new MaterialDialog.Builder(this)
                .title("程序运行时崩溃啦~")
                .content("是否选择分享最新的崩溃日志")
                .positiveText(R.string.ensure)
                .negativeText(R.string.cancel)
                .onPositive((dialog, which) -> ShareUtil.allShare(
                        new ShareUtil.ShareIntentBuilder(this)
                                .subject("分享到")
                                .title("分享")
                                .content(errorTrace)))
                .onNegative((dialog, which) -> {
                    //noinspection ResultOfMethodCallIgnored
                    errorTrace.delete();
                })
                .show();
    }

    /**
     * Checks if there is any missing permissions, and
     * requests runtime permission if needed.
     */
    private void checkAndRequestPermissions() {
        // Check for permissions
        for (String eachPermission : REQUIRED_PERMISSION_LIST) {
            if (ContextCompat.checkSelfPermission(this, eachPermission) != PackageManager.PERMISSION_GRANTED) {
                missingPermission.add(eachPermission);
            }
        }
        // Request for missing permissions
        if (!missingPermission.isEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this,
                    missingPermission.toArray(new String[0]),
                    REQUEST_PERMISSION_CODE);
        } else {
//            startSDKRegistration();
        }

    }


    /**
     * Result of runtime permission request
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Check for granted permission and remove from missing list
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = grantResults.length - 1; i >= 0; i--) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    missingPermission.remove(permissions[i]);
                }
            }
        }
        // 没有足够的权限时退出app
        if (!missingPermission.isEmpty()) {
            showToast("Missing permissions!!!");
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        Log.e(TAG, "onDestroy");
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private void initUI() {
        MoveScaleRotateView moveScaleRotateView = new MoveScaleRotateView(this);
        RelativeLayout view = findViewById(R.id.connection_activity);
        view.addView(moveScaleRotateView);

        mTextConnectionStatus = findViewById(R.id.text_connection_status);
        mTextProduct = findViewById(R.id.text_product_info);
        mBtnOpen = findViewById(R.id.btn_open);
        mBtnOpen.setOnClickListener(this);
        //按钮初始不可点击
//        mBtnOpen.setEnabled(false);

        TextView mVersionTv = findViewById(R.id.textView2);
        mVersionTv.setText(getResources().getString(R.string.sdk_version, DJISDKManager.getInstance().getSDKVersion()));
    }

    protected BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //当设备连接信息改变时刷新界面
            refreshSDKRelativeUI();
        }
    };

    private void refreshSDKRelativeUI() {
        BaseProduct mProduct = DJIDemoContext.getProductInstance();

        if (null != mProduct && mProduct.isConnected()) {
            Log.v(TAG, "refreshSDK: True");
            //当产品成功连接时，打开按钮置为 可点击
            mBtnOpen.setEnabled(true);

            //更新产品连接信息
            String str = mProduct instanceof Aircraft ? DJIAIRCRAFT : DJIHAND_HELD;
            mTextConnectionStatus.setText(getString(R.string.status_connected, str));

            if (null != mProduct.getModel()) {
                mTextProduct.setText(getString(R.string.null_string, mProduct.getModel().getDisplayName()));
            } else {
                mTextProduct.setText(R.string.product_information);
            }

        } else {
            //更新产品连接信息
            Log.v(TAG, "refreshSDK: False");
            mBtnOpen.setEnabled(false);

            mTextProduct.setText(R.string.product_information);
            mTextConnectionStatus.setText(R.string.connection_loose);
        }
    }

    /**
     * 处理点击事件
     *
     * @param v 被点击的组件
     */
    @SuppressLint("NonConstantResourceId")
    @SuppressWarnings("SwitchStatementWithTooFewBranches")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_open: {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                break;
            }
            default:
                break;
        }
    }

    private void showToast(final String toastMsg) {
        runOnUiThread(() -> Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_LONG).show());
    }
}
